package orderplan

import (
	"bytes"
	"encoding/json"
	"io/ioutil"
	"strconv"
	"oxy_server/model"
	"oxy_server/module/log"
	"oxy_server/until"
	"time"

	"oxy_server/res/cmsserver/designplan"
	"oxy_server/res/cmsserver/productproperty"
	"oxy_server/res/dicserver/dimensions"

	"github.com/labstack/echo"
	"github.com/rs/xid"
	"gopkg.in/mgo.v2/bson"
)

type (
	insertall struct {
		OrderNumber             string                     `json:"ordernumber" bson:"ordernumber"`                         //订单号
		Number                  string                     `json:"number" bson:"number"`                                   //流水号
		Price                   float64                    `json:"price" bson:"price"`                                     //零售价
		Markup                  float64                    `json:"markup" bson:"markup"`                                   //加价倍率
		HopeDesCTime            time.Time                  `json:"hopedesigncompletetime" bson:"hopedesigncompletetime"`   //期望设计完成日期
		HopeProCTime            time.Time                  `json:"hopeproductcompletetime" bson:"hopeproductcompletetime"` //期望生产完成日期
		Creuser                 string                     `json:"createuser" bson:"createuser"`                           //创建人
		Cretime                 time.Time                  `json:"createtime" bson:"createtime"`                           //创建时间
		Upduser                 string                     `json:"updateuser" bson:"updateuser"`                           //更新人
		Updtime                 time.Time                  `json:"updatetime" bson:"updatetime"`                           //更新时间
		RelPro                  string                     `json:"relpro" bson:"relpro"`                                   //关联生产组id
		ColorCountinfo          []ColorCount               `json:"colorsizeinfo" bson:"colorsizeinfo"`                     //颜色总数信息
		ProductId               bson.ObjectId              `json:"_id" bson:"_id"`                                         //品牌 生产组补录数据
		LargeCargoNumber        string                     `json:"largecargonumber" bson:"largecargonumber"`               //大货号
		Brand                   string                     `json:"brand" bson:"brand"`                                     //品牌
		Gender                  string                     `json:"gender" bson:"gender"`                                   //性别
		ProductCategory         string                     `json:"productcategory" bson:"productcategory"`                 //产品大类
		ProductKind             string                     `json:"productkind" bson:"productkind"`                         //品类
		Year                    string                     `json:"year" bson:"year"`                                       //年份
		Season                  string                     `json:"season" bson:"season"`                                   //季节
		Color                   []string                   `json:"color" bson:"color"`                                     //颜色
		DesignColor             []string                   `json:"designcolor" bson:"designcolor"`                         //设计组选择颜色
		Batch                   string                     `json:"batch" bson:"batch"`                                     //批次
		ModelName               string                     `json:"modelname" bson:"modelname"`                             //款式名称 设计组补录数据
		Productmode             string                     `json:"productmode" bson:"productmode"`                         //产品类型
		Factorynumber           string                     `json:"factorynumber" bson:"factorynumber"`                     //工厂款号
		Designer                string                     `json:"designer" bson:"designer"`                               //设计师
		DesignNumber            string                     `json:"designnumber" bson:"designnumber"`                       //设计号
		DesignPic               []string                   `json:"designpic" bson:"designpic"`                             //设计稿
		Picture                 []string                   `json:"picture" bson:"picture"`                                 //图片
		Provider                string                     `json:"provider" bson:"provider"`                               //供应商
		Tabs                    string                     `json:"tabs" bson:"tabs"`                                       // 物料单
		Dimensions              []dimensions.Dimensions    `json:"dimensions" bson:"dimensions"`                           // 设计组版师 尺寸规格表数据 版师补录数据
		RecommendedSize         []designplan.RecommendSize `json:"recommendsize" bson:"recommendsize"`                     // 设计组版师 尺码推荐表
		Editerstatus            int                        `json:"editerstatus" bson:"editerstatus"`                       //版师组状态
		Pattern                 []string                   `json:"pattern" bson:"pattern"`                                 // 版师组 纸样
		EditerCompleteTime      time.Time                  `json:"editercompletetime" bson:"editercompletetime"`           // 尺码推荐完成时间
		FollowUser              string                     `json:"followuser" bson:"followuser"`                           // 跟单员 11.1
		PropertyStatus          int                        `json:"propertystatus" bson:"propertystatus"`                   //生产组产品属性编辑状态
		Qualityreport           []string                   `json:"qualitytestreport" bson:"qualitytestreport"`             // 质检结果 11.4
		UploadWaterReport       []string                   `json:"uploadwaterreport" bson:"uploadwaterreport"`             // 水洗报告
		CertPic                 []string                   `json:"certpic" bson:"certpic"`                                 // 合格证报告
		WashPic                 []string                   `json:"washpic" bson:"washpic"`                                 // 水洗唛照片
		UploadTestReport        []string                   `json:"uploadtestreport" bson:"uploadtestreport"`               // 上传检测报告
		Packagecost             string                     `json:"packagecost" bson:"packagecost"`                         // 包装成本 11.4
		Processcost             []productproperty.Compose  `json:"processcost" bson:"processcost"`                         // 加工成本 11.4
		PackagecostTotal        float64                    `json:"packagecosttotal" bson:"packagecosttotal"`               // 包装成本合计 11.4
		ProcesscostTotal        float64                    `json:"processcosttotal" bson:"processcosttotal"`               // 加工成本合计 11.4
		Lock                    bool                       `json:"lock" bson:"lock"`                                       // 加工成本合计 11.4
		OrderCount              int                        `json:"ordercount" bson:"ordercount"`                           // 下单数量
		Count                   int                        `json:"count" bson:"count"`                                     // 入库数量
		InboundDate             time.Time                  `json:"inbounddate" bson:"inbounddate"`                         // 最近入库日期
		State                   string                     `json:"state" bson:"state"`                                     //阶段
		Opinion                 []OpinionInfo              `json:"opinion" bson:"opinion"`                                 // 批版意见
		Opinionstatus           int                        `json:"opinionstatus" bson:"opinionstatus"`                     //批版意见状态
		Designstatus            int                        `json:"designstatus" bson:"designstatus"`                       //设计组状态
		Technicalqualitycontrol int                        `json:"technicalqualitycontrol" bson:"technicalqualitycontrol"` //品控组状态
		Accountingstatus        int                        `json:"accountingstatus" bson:"accountingstatus"`               //核算状态
		Note                    string                     `json:"note" bson:"note"`                                       //产品运营备注
		DesignNote              string                     `json:"designnote" bson:"designnote"`                           //设计组备注
		TechnicalqualityNote    string                     `json:"technicalnote" bson:"technicalnote"`                     //技术品空备注
		PurchaseNote            string                     `json:"purchasesnote" bson:"purchasesnote"`                     //核价备注
		ProductNote             string                     `json:"productnote" bson:"productnote"`                         //生产备注
		WhetherImportErpInfo    string                     `json:"whetherimporterpinfo" bson:"whetherimporterpinfo"`       // erp 信息是否同步

	}
	Orderplan struct {
		ID bson.ObjectId `json:"_id" bson:"_id"`
		// OrderNumber    string        `json:"ordernumber" bson:"ordernumber"`                         //订单号
		Number         string       `json:"number" bson:"number"`                                   //流水号
		Price          float64      `json:"price" bson:"price"`                                     //零售价
		Markup         float64      `json:"markup" bson:"markup"`                                   //加价倍率
		HopeDesCTime   time.Time    `json:"hopedesigncompletetime" bson:"hopedesigncompletetime"`   //期望设计完成日期
		HopeProCTime   time.Time    `json:"hopeproductcompletetime" bson:"hopeproductcompletetime"` //期望生产完成日期
		Creuser        string       `json:"createuser" bson:"createuser"`                           //创建人
		Cretime        time.Time    `json:"createtime" bson:"createtime"`                           //创建时间
		Upduser        string       `json:"updateuser" bson:"updateuser"`                           //更新人
		Updtime        time.Time    `json:"updatetime" bson:"updatetime"`                           //更新时间
		RelPro         string       `json:"relpro" bson:"relpro"`                                   //关联生产组id
		Note           string       `json:"note" bson:"note"`                                       //备注
		ColorCountinfo []ColorCount `json:"colorsizeinfo" bson:"colorsizeinfo"`                     //颜色总数信息

	}
	insertorderplan struct {
		Number         string       `json:"number" bson:"number"`                                   //流水号
		Price          float64      `json:"price" bson:"price"`                                     //零售价
		Markup         float64      `json:"markup" bson:"markup"`                                   //加价倍率
		HopeDesCTime   time.Time    `json:"hopedesigncompletetime" bson:"hopedesigncompletetime"`   //期望设计完成日期
		HopeProCTime   time.Time    `json:"hopeproductcompletetime" bson:"hopeproductcompletetime"` //期望生产完成日期
		Creuser        string       `json:"createuser" bson:"createuser"`                           //创建人
		Cretime        time.Time    `json:"createtime" bson:"createtime"`                           //创建时间
		Upduser        string       `json:"updateuser" bson:"updateuser"`                           //更新人
		Updtime        time.Time    `json:"updatetime" bson:"updatetime"`                           //更新时间
		RelPro         string       `json:"relpro" bson:"relpro"`                                   //关联生产组id
		Note           string       `json:"note" bson:"note"`                                       //备注
		ColorCountinfo []ColorCount `json:"colorsizeinfo" bson:"colorsizeinfo"`                     //颜色总数信息
		State          string       `json:"state" bson:"state"`                                     //阶段
	}
	Product struct {
		ID                      bson.ObjectId              `json:"_id" bson:"_id"`
		OrderNumber             string                     `json:"ordernumber" bson:"ordernumber"`                         //订单号
		RelPro                  string                     `json:"relpro" bson:"relpro"`                                   //数据库id
		LargeCargoNumber        string                     `json:"largecargonumber" bson:"largecargonumber"`               //大货号
		Brand                   string                     `json:"brand" bson:"brand"`                                     //品牌
		Gender                  string                     `json:"gender" bson:"gender"`                                   //性别
		ProductCategory         string                     `json:"productcategory" bson:"productcategory"`                 //产品大类
		ProductKind             string                     `json:"productkind" bson:"productkind"`                         //品类
		Year                    string                     `json:"year" bson:"year"`                                       //年份
		Season                  string                     `json:"season" bson:"season"`                                   //季节
		Color                   []string                   `json:"color" bson:"color"`                                     //颜色
		DesignColor             []string                   `json:"designcolor" bson:"designcolor"`                         //设计组选择颜色
		Batch                   string                     `json:"batch" bson:"batch"`                                     //批次
		ModelName               string                     `json:"modelname" bson:"modelname"`                             //款式名称 设计补录
		Productmode             string                     `json:"productmode" bson:"productmode"`                         //产品类型
		Factorynumber           string                     `json:"factorynumber" bson:"factorynumber"`                     //工厂款号
		Designer                string                     `json:"designer" bson:"designer"`                               //设计师
		DesignNumber            string                     `json:"designnumber" bson:"designnumber"`                       //设计号
		DesignPic               []string                   `json:"designpic" bson:"designpic"`                             //设计稿
		Picture                 []string                   `json:"picture" bson:"picture"`                                 //图片
		Provider                string                     `json:"provider" bson:"provider"`                               //供应商
		Tabs                    string                     `json:"tabs" bson:"tabs"`                                       // 物料单
		Dimensions              []dimensions.Dimensions    `json:"dimensions" bson:"dimensions"`                           // 设计组版师 尺寸规格表数据 版师补录数据
		RecommendedSize         []designplan.RecommendSize `json:"recommendsize" bson:"recommendsize"`                     // 设计组版师 尺码推荐表
		Editerstatus            int                        `json:"editerstatus" bson:"editerstatus"`                       //版师组状态
		Pattern                 []string                   `json:"pattern" bson:"pattern"`                                 // 版师组 纸样
		EditerCompleteTime      time.Time                  `json:"editercompletetime" bson:"editercompletetime"`           // 尺码推荐完成时间
		FollowUser              string                     `json:"followuser" bson:"followuser"`                           // 跟单员 11.1
		PropertyStatus          int                        `json:"propertystatus" bson:"propertystatus"`                   //生产组产品属性编辑状态
		Qualityreport           []string                   `json:"qualitytestreport" bson:"qualitytestreport"`             // 质检结果 11.4
		UploadWaterReport       []string                   `json:"uploadwaterreport" bson:"uploadwaterreport"`             // 水洗报告
		CertPic                 []string                   `json:"certpic" bson:"certpic"`                                 // 合格证报告
		WashPic                 []string                   `json:"washpic" bson:"washpic"`                                 // 水洗唛照片
		UploadTestReport        []string                   `json:"uploadtestreport" bson:"uploadtestreport"`               // 上传检测报告
		Packagecost             string                     `json:"packagecost" bson:"packagecost"`                         // 包装成本 11.4
		Processcost             []productproperty.Compose  `json:"processcost" bson:"processcost"`                         // 加工成本 11.4
		PackagecostTotal        float64                    `json:"packagecosttotal" bson:"packagecosttotal"`               // 包装成本合计 11.4
		ProcesscostTotal        float64                    `json:"processcosttotal" bson:"processcosttotal"`               // 加工成本合计 11.4
		Lock                    bool                       `json:"lock" bson:"lock"`                                       // 加工成本合计 11.4
		OrderCount              int                        `json:"ordercount" bson:"ordercount"`                           // 下单数量
		Count                   int                        `json:"count" bson:"count"`                                     // 入库数量
		InboundDate             time.Time                  `json:"inbounddate" bson:"inbounddate"`                         // 最近入库日期
		State                   string                     `json:"state" bson:"state"`                                     //阶段
		Opinion                 []OpinionInfo              `json:"opinion" bson:"opinion"`                                 // 批版意见
		Opinionstatus           int                        `json:"opinionstatus" bson:"opinionstatus"`                     //批版意见状态
		Purcharesstatus         string                     `json:"purchasesstatus" bson:"purchasesstatus"`                 //采购下单状态
		Designstatus            int                        `json:"designstatus" bson:"designstatus"`                       //设计组状态
		Technicalqualitycontrol int                        `json:"technicalqualitycontrol" bson:"technicalqualitycontrol"` //品控组状态
		Accountingstatus        int                        `json:"accountingstatus" bson:"accountingstatus"`               //核算状态
		DesignNote              string                     `json:"designnote" bson:"designnote"`                           //设计组备注
		TechnicalqualityNote    string                     `json:"technicalnote" bson:"technicalnote"`                     //技术品空备注
		PurchaseNote            string                     `json:"purchasesnote" bson:"purchasesnote"`                     //核价备注
		ProductNote             string                     `json:"productnote" bson:"productnote"`                         //备注
		WhetherImportErpInfo    string                     `json:"whetherimporterpinfo" bson:"whetherimporterpinfo"`       // erp 信息是否同步
	}
	UpdateProduct struct {
		RelPro           string   `json:"relpro" bson:"relpro"`                     //关联生产组id
		LargeCargoNumber string   `json:"largecargonumber" bson:"largecargonumber"` //大货号
		Brand            string   `json:"brand" bson:"brand"`                       //品牌
		Gender           string   `json:"gender" bson:"gender"`                     //性别
		ProductCategory  string   `json:"productcategory" bson:"productcategory"`   //产品大类
		ProductKind      string   `json:"productkind" bson:"productkind"`           //品类
		Year             string   `json:"year" bson:"year"`                         //年份
		Season           string   `json:"season" bson:"season"`                     //季节
		Color            []string `json:"color" bson:"color"`                       //颜色
		Batch            string   `json:"batch" bson:"batch"`                       //批次
		// Type            string   `json:"type" bson:"type"`                       //原有生产组为plan 订单模式生产组数据order
		State       string `json:"state" bson:"state"`             //阶段
		OrderNumber string `json:"ordernumber" bson:"ordernumber"` //订单号

	}

	DesignInfo struct {
		RelPro           string   `json:"relpro" bson:"relpro"`                     //关联生产组id
		ModelName        string   `json:"modelname" bson:"modelname"`               //款式名称
		Productmode      string   `json:"productmode" bson:"productmode"`           //产品类型
		Factorynumber    string   `json:"factorynumber" bson:"factorynumber"`       //工厂款号
		Designer         string   `json:"designer" bson:"designer"`                 //设计师
		DesignNumber     string   `json:"designnumber" bson:"designnumber"`         //设计号
		DesignPic        []string `json:"designpic" bson:"designpic"`               //设计稿
		Picture          []string `json:"picture" bson:"picture"`                   //图片
		Provider         string   `json:"provider" bson:"provider"`                 //供应商
		Designstatus     int      `json:"designstatus" bson:"designstatus"`         //设计组状态
		Tabs             string   `json:"tabs" bson:"tabs"`                         // 物料单
		ProductNote      string   `json:"productnote" bson:"productnote"`           //备注
		DesignColor      []string `json:"designcolor" bson:"designcolor"`           //颜色
		Packagecost      string   `json:"packagecost" bson:"packagecost"`           // 包装成本 11.4
		PackagecostTotal float64  `json:"packagecosttotal" bson:"packagecosttotal"` // 包装成本合计 11.4
		State            string   `json:"state" bson:"state"`                       //阶段
		Accountingstatus int      `json:"accountingstatus" bson:"accountingstatus"` //核算状态
		DesignNote       string   `json:"designnote" bson:"designnote"`             //设计组备注
		PurchaseNote     string   `json:"purchasesnote" bson:"purchasesnote"`       //核价备注
	}

	QualityInfo struct {
		RelPro                  string   `json:"relpro" bson:"relpro"`                                   //关联生产组id
		ModelName               string   `json:"modelname" bson:"modelname"`                             //款式名称
		Productmode             string   `json:"productmode" bson:"productmode"`                         //产品类型
		Factorynumber           string   `json:"factorynumber" bson:"factorynumber"`                     //工厂款号
		Designer                string   `json:"designer" bson:"designer"`                               //设计师
		DesignNumber            string   `json:"designnumber" bson:"designnumber"`                       //设计号
		DesignPic               []string `json:"designpic" bson:"designpic"`                             //设计稿
		Picture                 []string `json:"picture" bson:"picture"`                                 //图片
		Provider                string   `json:"provider" bson:"provider"`                               //供应商
		Tabs                    string   `json:"tabs" bson:"tabs"`                                       // 物料单
		ProductNote             string   `json:"productnote" bson:"productnote"`                         //备注
		DesignColor             []string `json:"designcolor" bson:"designcolor"`                         //颜色
		Packagecost             string   `json:"packagecost" bson:"packagecost"`                         // 包装成本 11.4
		PackagecostTotal        float64  `json:"packagecosttotal" bson:"packagecosttotal"`               // 包装成本合计 11.4
		State                   string   `json:"state" bson:"state"`                                     //阶段
		CertPic                 []string `json:"certpic" bson:"certpic"`                                 // 合格证报告
		WashPic                 []string `json:"washpic" bson:"washpic"`                                 // 水洗唛照片
		Qualityreport           []string `json:"qualitytestreport" bson:"qualitytestreport"`             // 质检结果 11.4
		UploadWaterReport       []string `json:"uploadwaterreport" bson:"uploadwaterreport"`             // 水洗报告
		UploadTestReport        []string `json:"uploadtestreport" bson:"uploadtestreport"`               // 上传检测报告
		Technicalqualitycontrol int      `json:"technicalqualitycontrol" bson:"technicalqualitycontrol"` //品控组状态
		TechnicalqualityNote    string   `json:"technicalnote" bson:"technicalnote"`                     //技术品空备注
	}

	DesignEditer struct {
		Dimensions         []dimensions.Dimensions    `json:"dimensions" bson:"dimensions"`                 // 设计组版师 尺寸规格表数据
		RecommendedSize    []designplan.RecommendSize `json:"recommendsize" bson:"recommendsize"`           // 设计组版师 尺码推荐表
		Pattern            []string                   `json:"pattern" bson:"pattern"`                       // 版师组 纸样
		Editerstatus       int                        `json:"editerstatus" bson:"editerstatus"`             //版师组状态
		EditerCompleteTime time.Time                  `json:"editercompletetime" bson:"editercompletetime"` // 尺码推荐完成时间

	}
	ProductBase struct {
		LargeCargoNumber     string                    `json:"largecargonumber" bson:"largecargonumber"`         //大货号
		Brand                string                    `json:"brand" bson:"brand"`                               //品牌
		ProductKind          string                    `json:"productkind" bson:"productkind"`                   //品类
		ModelName            string                    `json:"modelname" bson:"modelname"`                       //款式名称 设计补录
		Factorynumber        string                    `json:"factorynumber" bson:"factorynumber"`               //工厂款号
		Color                []string                  `json:"color" bson:"color"`                               //颜色
		Designer             string                    `json:"designer" bson:"designer"`                         //设计师
		Batch                string                    `json:"batch" bson:"batch"`                               //批次
		Provider             string                    `json:"provider" bson:"provider"`                         //供应商
		Gender               string                    `json:"gender" bson:"gender"`                             //性别
		FollowUser           string                    `json:"followuser" bson:"followuser"`                     // 跟单员 11.1
		PropertyStatus       int                       `json:"propertystatus" bson:"propertystatus"`             //生产组产品属性编辑状态
		Qualityreport        []string                  `json:"qualitytestreport" bson:"qualitytestreport"`       // 质检结果 11.4
		UploadWaterReport    []string                  `json:"uploadwaterreport" bson:"uploadwaterreport"`       // 水洗报告
		CertPic              []string                  `json:"certpic" bson:"certpic"`                           // 合格证报告
		WashPic              []string                  `json:"washpic" bson:"washpic"`                           // 水洗唛照片
		UploadTestReport     []string                  `json:"uploadtestreport" bson:"uploadtestreport"`         // 上传检测报告
		Tabs                 string                    `json:"tabs" bson:"tabs"`                                 // 物料单
		Packagecost          string                    `json:"packagecost" bson:"packagecost"`                   // 包装成本 11.4
		Processcost          []productproperty.Compose `json:"processcost" bson:"processcost"`                   // 加工成本 11.4
		PackagecostTotal     float64                   `json:"packagecosttotal" bson:"packagecosttotal"`         // 包装成本合计 11.4
		ProcesscostTotal     float64                   `json:"processcosttotal" bson:"processcosttotal"`         // 加工成本合计 11.4
		Lock                 bool                      `json:"lock" bson:"lock"`                                 // 加工成本合计 11.4
		Productmode          string                    `json:"productmode" bson:"productmode"`                   //产品类型
		WhetherImportErpInfo string                    `json:"whetherimporterpinfo" bson:"whetherimporterpinfo"` // erp 信息是否同步
	}

	ProductQualityOpinion struct {
		RelPro           string        `json:"relpro" bson:"relpro"`                     //关联生产组id
		LargeCargoNumber string        `json:"largecargonumber" bson:"largecargonumber"` //大货号
		Opinion          []OpinionInfo `json:"opinion" bson:"opinion"`                   // 批版意见
		Opinionstatus    int           `json:"opinionstatus" bson:"opinionstatus"`       //批版意见状态

	}
	OpinionInfo struct {
		Desc string   `json:"desc" bson:"desc"`
		Pic  []string `json:"pic" bson:"pic"`
	}
	ColorCount struct {
		Color string `json:"color" bson:"color"` //颜色
		Count int    `json:"count" bson:"count"` //总数

	}
	RelProList struct {
		RelPro string `json:"relpro" bson:"relpro"` //关联生产组id
	}
)

type OXYOrderModeData struct{}

func NewOXYOrderModeData() *OXYOrderModeData {
	Data := &OXYOrderModeData{}
	return Data
}

func (opd *OXYOrderModeData) AddOrderModeHandler(c echo.Context) error {

	log.Info("AddOrderModeHandler")
	all := &insertall{}
	// p := c
	if err := c.Bind(all); err != nil {
		log.Error("创建订单,解析参数错误", err)
		c.JSON(403, map[string]interface{}{
			"msg":  "error",
			"info": err,
		})
		return err
	}
	id := xid.New().String()
	productId := bson.NewObjectId()
	product := &Product{
		ID:               productId,
		LargeCargoNumber: all.LargeCargoNumber,
		RelPro:           id,
		Brand:            all.Brand,
		Gender:           all.Gender,
		ProductCategory:  all.ProductCategory,
		ProductKind:      all.ProductKind,
		Year:             all.Year,
		Season:           all.Season,
		Color:            all.Color,
		Batch:            all.Batch,
		State:            all.State,
		OrderNumber:      all.OrderNumber,
	}
	order := &insertorderplan{
		Number:         all.Number,
		Price:          all.Price,
		Markup:         all.Markup,
		HopeDesCTime:   all.HopeDesCTime,
		HopeProCTime:   all.HopeProCTime,
		Creuser:        all.Creuser,
		Cretime:        time.Now(),
		Upduser:        all.Upduser,
		Updtime:        time.Now(),
		RelPro:         id,
		Note:           all.Note,
		ColorCountinfo: all.ColorCountinfo,
	}

	order.RelPro = id
	product.RelPro = id
	log.Info("id", id)
	model.DB().Dbname = "OxyCms"
	model.DB().Document = "product_plan_order"
	err := model.DB().Insert(product)
	if err != nil {
		log.Error("创建订单,插入生产数据失败", err)
		c.JSON(403, map[string]interface{}{
			"msg":  "error",
			"info": err,
		})
		return err
	}
	model.DB().Document = "order_mode"
	err = model.DB().Insert(order)
	if err != nil {
		log.Error("创建订单,插入订单数据失败", err)
		c.JSON(403, map[string]interface{}{
			"msg":  "error",
			"info": err,
		})
		return err
	}
	model.DB().Dbname = "OxyDic"
	model.DB().Document = "serialNumber"
	selector := bson.M{"brand": product.Brand, "number": order.Number}
	data := bson.M{"$set": bson.M{"flag": "1"}}
	err = model.DB().Update(selector, data)
	if err != nil {
		log.Error("更新流水号表出错", err)
	}
	c.JSON(200, map[string]interface{}{
		"msg":  "success",
		"data": productId,
	})

	return nil
}

func (opd *OXYOrderModeData) UpdateOrderModeHandler(c echo.Context) error {
	id := c.QueryParam("id")
	log.Info("UpdateOrderModeHandler")
	all := &insertall{}
	// p := c
	if err := c.Bind(all); err != nil {
		log.Error("创建订单,解析参数错误", err)
		c.JSON(403, map[string]interface{}{
			"msg":  "error",
			"info": err,
		})
		return err
	}
	selector := bson.M{"relpro": id}
	product := &UpdateProduct{
		RelPro:           all.RelPro,
		Brand:            all.Brand,
		LargeCargoNumber: all.LargeCargoNumber,
		Gender:           all.Gender,
		ProductCategory:  all.ProductCategory,
		ProductKind:      all.ProductKind,
		Year:             all.Year,
		Season:           all.Season,
		Color:            all.Color,
		Batch:            all.Batch,
		OrderNumber:      all.OrderNumber,
		State:            all.State,
	}
	order := &insertorderplan{
		Number:         all.Number,
		Price:          all.Price,
		Markup:         all.Markup,
		HopeDesCTime:   all.HopeDesCTime,
		HopeProCTime:   all.HopeProCTime,
		Creuser:        all.Creuser,
		Cretime:        all.Cretime,
		Upduser:        all.Upduser,
		Updtime:        time.Now(),
		RelPro:         all.RelPro,
		Note:           all.Note,
		ColorCountinfo: all.ColorCountinfo,
	}
	model.DB().Dbname = "OxyCms"
	model.DB().Document = "product_plan_order"

	p := Product{}
	query, err := model.DB().QueryOne(selector)
	query.One(&p)
	s, err := json.Marshal(p)
	bufbody := bytes.NewBuffer(s)
	c.Request().Body = ioutil.NopCloser(bufbody)

	err = model.DB().Update(selector, bson.M{"$set": product})

	if err != nil {
		log.Error("创建订单,插入生产数据失败", err)
		c.JSON(403, map[string]interface{}{
			"msg":  "error",
			"info": err,
		})
		return err
	}
	model.DB().Document = "order_mode"
	err = model.DB().Update(selector, bson.M{"$set": order})
	if err != nil {
		log.Error("创建订单,插入订单数据失败", err)
		c.JSON(403, map[string]interface{}{
			"msg":  "error",
			"info": err,
		})
		return err
	}

	c.JSON(200, map[string]interface{}{
		"msg": "success",
	})

	return nil
}

// 设计组维护产品 属性
func (opd *OXYOrderModeData) DesignUpdateProductHandler(c echo.Context) error {
	id := c.QueryParam("id")
	log.Info("DesignUpdateProductHandler:", id)
	all := &DesignInfo{}
	if err := c.Bind(all); err != nil {
		log.Error("设计组更新产品属性,解析参数错误", err)
		c.JSON(403, map[string]interface{}{
			"msg":  "error",
			"info": err,
		})
		return err
	}
	selector := bson.M{"relpro": id}
	model.DB().Dbname = "OxyCms"
	model.DB().Document = "product_plan_order"

	p := DesignInfo{}
	query, err := model.DB().QueryOne(selector)
	query.One(&p)
	s, err := json.Marshal(p)
	bufbody := bytes.NewBuffer(s)
	c.Request().Body = ioutil.NopCloser(bufbody)

	err = model.DB().Update(selector, bson.M{"$set": all})
	if err != nil {
		log.Error("创建订单,插入生产数据失败", err)
		c.JSON(403, map[string]interface{}{
			"msg":  "error",
			"info": err,
		})
		return err
	}
	c.JSON(200, map[string]interface{}{
		"msg": "success",
	})

	return nil
}

// 品控组组维护产品 属性
func (opd *OXYOrderModeData) QualityUpdateProductHandler(c echo.Context) error {
	id := c.QueryParam("id")
	log.Info("QualityUpdateProductHandler:", id)
	all := &QualityInfo{}
	if err := c.Bind(all); err != nil {
		log.Error("设计组更新产品属性,解析参数错误", err)
		c.JSON(403, map[string]interface{}{
			"msg":  "error",
			"info": err,
		})
		return err
	}
	selector := bson.M{"relpro": id}
	model.DB().Dbname = "OxyCms"
	model.DB().Document = "product_plan_order"
	p := QualityInfo{}
	query, err := model.DB().QueryOne(selector)
	query.One(&p)
	s, err := json.Marshal(p)
	bufbody := bytes.NewBuffer(s)
	c.Request().Body = ioutil.NopCloser(bufbody)
	err = model.DB().Update(selector, bson.M{"$set": all})
	if err != nil {
		log.Error("创建订单,插入生产数据失败", err)
		c.JSON(403, map[string]interface{}{
			"msg":  "error",
			"info": err,
		})
		return err
	}
	c.JSON(200, map[string]interface{}{
		"msg": "success",
	})

	return nil
}

// 品控组组维护产品 批版意见
func (opd *OXYOrderModeData) QualityUpdateProductOpinionHandler(c echo.Context) error {
	id := c.QueryParam("id")
	log.Info("QualityUpdateProductOpinionHandler:", id)
	all := &ProductQualityOpinion{}
	if err := c.Bind(all); err != nil {
		log.Error("品控组更新批版意见", err)
		c.JSON(403, map[string]interface{}{
			"msg":  "error",
			"info": err,
		})
		return err
	}
	selector := bson.M{"relpro": id}
	model.DB().Dbname = "OxyCms"
	model.DB().Document = "product_plan_order"
	p := ProductQualityOpinion{}
	query, err := model.DB().QueryOne(selector)
	query.One(&p)
	s, err := json.Marshal(p)
	bufbody := bytes.NewBuffer(s)
	c.Request().Body = ioutil.NopCloser(bufbody)
	err = model.DB().Update(selector, bson.M{"$set": all})
	if err != nil {
		log.Error("品控组更新批版意见失败", err)
		c.JSON(403, map[string]interface{}{
			"msg":  "error",
			"info": err,
		})
		return err
	}
	c.JSON(200, map[string]interface{}{
		"msg": "success",
	})

	return nil
}

// 设计组维护产品 版师属性
func (opd *OXYOrderModeData) DesignUpdateEditerHandler(c echo.Context) error {
	id := c.QueryParam("id")
	log.Info("DesignUpdateProductHandler:", id)
	all := &DesignEditer{}
	if err := c.Bind(all); err != nil {
		log.Error("设计组更新版师,解析参数错误", err)
		c.JSON(403, map[string]interface{}{
			"msg":  "error",
			"info": err,
		})
		return err
	}
	selector := bson.M{"relpro": id}
	model.DB().Dbname = "OxyCms"
	model.DB().Document = "product_plan_order"
	p := DesignEditer{}
	query, err := model.DB().QueryOne(selector)
	query.One(&p)
	s, err := json.Marshal(p)
	bufbody := bytes.NewBuffer(s)
	c.Request().Body = ioutil.NopCloser(bufbody)
	err = model.DB().Update(selector, bson.M{"$set": all})
	if err != nil {
		log.Error("创建订单,插入生产数据失败", err)
		c.JSON(403, map[string]interface{}{
			"msg":  "error",
			"info": err,
		})
		return err
	}
	c.JSON(200, map[string]interface{}{
		"msg": "success",
	})

	return nil
}

// 生产组维护产品 基础属性
func (opd *OXYOrderModeData) ProductUpdateBaseHandler(c echo.Context) error {
	id := c.QueryParam("id")
	log.Info("DesignUpdateProductHandler:", id)
	all := &ProductBase{}
	if err := c.Bind(all); err != nil {
		log.Error("生产组更新产品属性,解析参数错误", err)
		c.JSON(403, map[string]interface{}{
			"msg":  "error",
			"info": err,
		})
		return err
	}
	selector := bson.M{"relpro": id}
	model.DB().Dbname = "OxyCms"
	model.DB().Document = "product_plan_order"
	p := ProductBase{}
	query, err := model.DB().QueryOne(selector)
	query.One(&p)
	s, err := json.Marshal(p)
	bufbody := bytes.NewBuffer(s)
	c.Request().Body = ioutil.NopCloser(bufbody)
	err = model.DB().Update(selector, bson.M{"$set": all})
	if err != nil {
		log.Error("创建订单,插入生产数据失败", err)
		c.JSON(403, map[string]interface{}{
			"msg":  "error",
			"info": err,
		})
		return err
	}
	c.JSON(200, map[string]interface{}{
		"msg": "success",
	})

	return nil
}

// 采购更新是否采购
func (opd *OXYOrderModeData) PurchasesUpdateStatusHandler(c echo.Context) error {
	status := c.QueryParam("status")
	jsonquery := c.QueryParam("like")
	M, err := until.JsonToBson(jsonquery)
	if err != nil {
		log.Error("json-> bson 失败", err)
		c.JSON(403, map[string]interface{}{
			"msg": "error",
		})
		return err
	}
	log.Info("PurchasesUpdateStatusHandler:")
	model.DB().Dbname = "OxyCms"
	model.DB().Document = "product_plan_order"
	_, err = model.DB().UpdateAll(M, bson.M{"$set": bson.M{"purchasesstatus": status}})
	if err != nil {
		log.Error("更新产品是否下单", err)
		c.JSON(403, map[string]interface{}{
			"msg":  "error",
			"info": err,
		})
		return err
	}
	c.JSON(200, map[string]interface{}{
		"msg": "success",
	})

	return nil
}
func (opd *OXYOrderModeData) GetOrderModeListHandler(c echo.Context) error {
	currentpage, err := strconv.Atoi(c.QueryParam("currentpage"))
	perpage, err := strconv.Atoi(c.QueryParam("perpage"))
	jsonquery := c.QueryParam("like")
	if err != nil {
		log.Error("解析参数错误", err)
		c.JSON(403, map[string]interface{}{
			"msg": "error",
		})
		return err
	}
	model.DB().Dbname = "OxyCms"
	model.DB().Document = "product_plan_order"
	M, err := until.JsonToBson(jsonquery)
	if err != nil {
		log.Error("json-> bson 失败", err)
		c.JSON(403, map[string]interface{}{
			"msg": "error",
		})
		return err
	}
	query, count, err := model.DB().QuerySort(M, currentpage, perpage, "_id")
	if err != nil {
		log.Error("查询出错,product_plan_order:", err)
		c.JSON(404, map[string]interface{}{
			"msg": "error",
		})
		return err
	}
	ps := []Orderplan{}
	productList := []Product{}
	List := []insertall{}
	query.All(&productList)
	queryRelList := []RelProList{}
	for _, v := range productList {
		queryRelList = append(queryRelList, RelProList{
			RelPro: v.RelPro,
		})
	}
	if len(queryRelList) == 0 {
		c.JSON(200, map[string]interface{}{
			"msg":   "success",
			"data":  List,
			"count": 0,
		})
		return nil
	}
	model.DB().Document = "order_mode"
	productQuery, _, err := model.DB().Query(bson.M{"$or": queryRelList}, 0, 0)
	if err != nil {
		log.Error("查询出错,order_mode:", err)
		c.JSON(404, map[string]interface{}{
			"msg": "error",
		})
		return err
	}
	productQuery.All(&ps)
	for _, o := range ps {
		for _, p := range productList {
			if p.RelPro == o.RelPro {
				data := insertall{
					LargeCargoNumber:        p.LargeCargoNumber,
					Number:                  o.Number,
					Price:                   o.Price,
					Markup:                  o.Markup,
					HopeDesCTime:            o.HopeDesCTime,
					HopeProCTime:            o.HopeProCTime,
					Creuser:                 o.Creuser,
					Cretime:                 o.Cretime,
					Upduser:                 o.Upduser,
					Updtime:                 o.Updtime,
					RelPro:                  o.RelPro,
					Note:                    o.Note,
					ColorCountinfo:          o.ColorCountinfo,
					OrderNumber:             p.OrderNumber,
					ProductId:               p.ID,
					Brand:                   p.Brand,
					Gender:                  p.Gender,
					ProductCategory:         p.ProductCategory,
					ProductKind:             p.ProductKind,
					Year:                    p.Year,
					Season:                  p.Season,
					Color:                   p.Color,
					Batch:                   p.Batch,
					Picture:                 p.Picture,
					Productmode:             p.Productmode,
					ModelName:               p.ModelName,
					Factorynumber:           p.Factorynumber,
					Provider:                p.Provider,
					ProductNote:             p.ProductNote,
					Designstatus:            p.Designstatus,
					Editerstatus:            p.Editerstatus,
					DesignNumber:            p.DesignNumber,
					Designer:                p.Designer,
					DesignPic:               p.DesignPic,
					FollowUser:              p.FollowUser,
					InboundDate:             p.InboundDate,
					OrderCount:              p.OrderCount,
					Count:                   p.Count,
					State:                   p.State,
					Opinionstatus:           p.Opinionstatus,
					Tabs:                    p.Tabs,
					Technicalqualitycontrol: p.Technicalqualitycontrol,
					Accountingstatus:        p.Accountingstatus,
					DesignNote:              p.DesignNote,
					TechnicalqualityNote:    p.TechnicalqualityNote,
					PurchaseNote:            p.PurchaseNote,
					Packagecost:             p.Packagecost,
					PropertyStatus:          p.PropertyStatus,
				}
				List = append(List, data)
			}
		}
	}
	if err != nil {
		log.Error("解析参数错误", err)
		c.JSON(403, map[string]interface{}{
			"msg": "error",
		})
		return err
	}
	c.JSON(200, map[string]interface{}{
		"msg":   "success",
		"data":  List,
		"count": count,
	})

	return nil

}

func (opd *OXYOrderModeData) GetOrderModeInfoHandler(c echo.Context) error {
	id := c.QueryParam("id")
	model.DB().Dbname = "OxyCms"
	model.DB().Document = "order_mode"
	queryorder, err := model.DB().QueryOne(bson.M{"relpro": id})
	if err != nil {
		log.Error("GetOrderModeInfoHandler 查询失败", err)
		c.JSON(404, map[string]interface{}{
			"msg": "error",
		})
		return err
	}
	model.DB().Document = "product_plan_order"
	queryproduct, err := model.DB().QueryOne(bson.M{"relpro": id})
	if err != nil {
		log.Error("GetOrderModeInfoHandler 查询失败", err)
		c.JSON(404, map[string]interface{}{
			"msg": "error",
		})
		return err
	}
	order := Orderplan{}
	p := Product{}

	err = queryorder.One(&order)
	if err != nil {
		log.Error("GetOrderModeInfoHandler 解析失败", err)
		c.JSON(403, map[string]interface{}{
			"msg": "error",
		})
		return err
	}
	err = queryproduct.One(&p)
	if err != nil {
		log.Error("GetOrderModeInfoHandler 解析失败", err)
		c.JSON(403, map[string]interface{}{
			"msg": "error",
		})
		return err
	}
	data := insertall{
		OrderNumber:             p.OrderNumber,
		LargeCargoNumber:        p.LargeCargoNumber,
		Number:                  order.Number,
		Price:                   order.Price,
		Markup:                  order.Markup,
		HopeDesCTime:            order.HopeDesCTime,
		HopeProCTime:            order.HopeProCTime,
		Creuser:                 order.Creuser,
		Cretime:                 order.Cretime,
		Upduser:                 order.Upduser,
		Updtime:                 order.Updtime,
		RelPro:                  order.RelPro,
		Note:                    order.Note,
		ColorCountinfo:          order.ColorCountinfo,
		ProductId:               p.ID,
		Brand:                   p.Brand,
		Gender:                  p.Gender,
		ProductCategory:         p.ProductCategory,
		ProductKind:             p.ProductKind,
		Year:                    p.Year,
		Season:                  p.Season,
		Color:                   p.Color,
		Batch:                   p.Batch,
		ModelName:               p.ModelName,
		Productmode:             p.Productmode,
		Factorynumber:           p.Factorynumber,
		DesignNumber:            p.DesignNumber,
		Designer:                p.Designer,
		DesignPic:               p.DesignPic,
		Picture:                 p.Picture,
		Provider:                p.Provider,
		Designstatus:            p.Designstatus,
		Tabs:                    p.Tabs,
		Dimensions:              p.Dimensions,
		RecommendedSize:         p.RecommendedSize,
		ProductNote:             p.ProductNote,
		Pattern:                 p.Pattern,
		Editerstatus:            p.Editerstatus,
		EditerCompleteTime:      p.EditerCompleteTime,
		FollowUser:              p.FollowUser,
		PropertyStatus:          p.PropertyStatus,
		Qualityreport:           p.Qualityreport,
		UploadWaterReport:       p.UploadWaterReport,
		CertPic:                 p.CertPic,
		WashPic:                 p.WashPic,
		UploadTestReport:        p.UploadTestReport,
		Packagecost:             p.Packagecost,
		Processcost:             p.Processcost,
		PackagecostTotal:        p.PackagecostTotal,
		ProcesscostTotal:        p.ProcesscostTotal,
		Lock:                    p.Lock,
		DesignColor:             p.DesignColor,
		State:                   p.State,
		Opinion:                 p.Opinion,
		Opinionstatus:           p.Opinionstatus,
		Technicalqualitycontrol: p.Technicalqualitycontrol,
		Accountingstatus:        p.Accountingstatus,
		DesignNote:              p.DesignNote,
		TechnicalqualityNote:    p.TechnicalqualityNote,
		PurchaseNote:            p.PurchaseNote,
		WhetherImportErpInfo:    p.WhetherImportErpInfo,
	}

	c.JSON(200, map[string]interface{}{
		"msg":  "success",
		"data": data,
	})
	return nil
}

func (opd *OXYOrderModeData) DelOrderModeHandler(c echo.Context) error {
	id := c.QueryParam("id")
	productid := c.QueryParam("productid")
	if id == "" || productid == "" {
		c.JSON(403, map[string]interface{}{
			"msg":  "error",
			"info": "参数错误",
		})
		return nil
	}
	order := Orderplan{}
	product := Product{}
	model.DB().Dbname = "OxyCms"
	model.DB().Document = "order_mode"
	queryorder, err := model.DB().QueryOne(bson.M{"relpro": id})
	if err != nil {
		log.Error("GetOrderModeInfoHandler 查询失败", err)
	}
	model.DB().Document = "product_plan_order"
	queryproduct, err := model.DB().QueryOne(bson.M{"relpro": id})
	if err != nil {
		log.Error("GetOrderModeInfoHandler 查询失败", err)
	}

	err = queryorder.One(&order)
	if err != nil {
		log.Error("GetOrderModeInfoHandler 解析失败", err)
	}
	err = queryproduct.One(&product)
	if err != nil {
		log.Error("GetOrderModeInfoHandler 解析失败", err)
	}

	model.DB().Dbname = "OxyCms"
	model.DB().Document = "order_mode"

	err = model.DB().Remove(bson.M{"relpro": id})
	if err != nil {
		log.Error("删除出错 order_mode", err)
	}
	model.DB().Document = "product_plan_order"
	err = model.DB().Remove(bson.M{"relpro": id})
	if err != nil {
		log.Error("删除出错 product_plan_order", err)
	}

	model.DB().Dbname = "OxyDic"
	model.DB().Document = "serialNumber"
	selector := bson.M{"brand": product.Brand, "number": order.Number}
	data := bson.M{"$set": bson.M{"flag": "0"}}
	err = model.DB().Update(selector, data)
	if err != nil {
		log.Error("更新流水号表出错", err)
	}
	model.DB().Dbname = "OxyCms"
	model.DB().Document = "sku"
	_, err = model.DB().RemoveAll(bson.M{"productctiongroupid": productid})
	if err != nil {
		log.Error("删除sku出错", err)
		c.JSON(404, map[string]interface{}{
			"msg": "error",
		})
	}

	c.JSON(200, map[string]interface{}{
		"msg": "success",
	})

	return nil
}
